package org.net5ijy.security.config.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import org.springframework.core.convert.converter.Converter;

/**
 * DateConverter
 *
 * @author XGF
 * @date 2020/11/30 22:30
 */
public class DateConverter implements Converter<String, Date> {

  private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
  private static SimpleDateFormat ymdhms =
      new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  private static Pattern ymdPattern = Pattern
      .compile("^\\d{4}-\\d{2}-\\d{2}$");
  private static Pattern ymdhmsPattern = Pattern
      .compile("^\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}:\\d{2}$");

  @Override
  public Date convert(String source) {
    try {
      if (ymdPattern.matcher(source).find()) {
        return ymd.parse(source);
      }
      if (ymdhmsPattern.matcher(source).find()) {
        return ymdhms.parse(source);
      }
    } catch (ParseException ignored) {
    }
    return null;
  }
}
